import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

//波浪
class LearnWavePage extends StatefulWidget {
  @override
  _LearnWavePageState createState() => _LearnWavePageState();
}

class _LearnWavePageState extends State<LearnWavePage>
    with SingleTickerProviderStateMixin {
  StreamController<double> _streamController;

  @override
  void initState() {
    super.initState();

    _streamController = StreamController();
    _streamController
        .addStream(Stream.periodic(Duration(milliseconds: 200), (index) {
      return 0.6 * index;
    }));
  }

  @override
  void dispose() {
    _streamController.close();

    super.dispose();
  }

  //返回数据流
  // Stream<double> _readStreamData() {
  //   return _streamController.stream;
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          //线性容器
          _clipWaveAnimation(context),
        ],
      ),
    );
  }

  //动画控制器裁剪水纹
  Widget _clipWaveAnimation(BuildContext context) {
    double number = 0.6;
    return StreamBuilder(
        initialData: 0.0,
        stream: _streamController.stream,
        // Stream.periodic(Duration(milliseconds: 150), (index) {
        //   print("index---:${index}");
        //   return number * index;
        // }),
        builder: (context, snape) {
          print("获取的数据---:${snape.data}");
          return ClipPath(
            clipper: ZdyClipper(clipProgress: snape.data),
            child: _buildLineContainer(context),
          );
        });
  }

  //线性容器
  Widget _buildLineContainer(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * .45,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.orange, Colors.deepOrangeAccent],
        ),
      ),
    );
  }
}

class ZdyClipper extends CustomClipper<Path> {
  double clipProgress;

  ZdyClipper({this.clipProgress = 0});

  @override
  Path getClip(Size size) {
    Path _path = Path();
    double dy = 0;
    //振幅
    double waveA = 15.0;
    //周期
    double waveW = 0.5 / 30.0;

    print("w---:${waveW}");

    _path.moveTo(0, 0);
    _path.lineTo(0, size.height * 0.8);
    for (int i = 0; i < size.width; i++) {
      dy = size.height * 0.8 + waveA * sin(waveW * i + clipProgress * 20);
      _path.lineTo(i.toDouble(), dy);
    }

    _path.lineTo(size.width, size.height * 0.8);
    _path.lineTo(size.width, 0);

    print("dy-----:${dy}");

    return _path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return true;
  }
}
